# -*- coding: utf-8 -*-
import streamlit as st

st.set_page_config(
    page_title="智能招聘分析平台",
    page_icon="💼",
    layout="wide",
    initial_sidebar_state="expanded"
)

import pandas as pd
import plotly.express as px
import re

# 导入功能模块
from modules.data_analysis import render_data_analysis
from modules.skill_graph import render_skill_graph
from modules.ai_chat import render_ai_chat

# ========== 全局配置 ==========

# ========== 主应用框架 ==========
def main():
    # ========== 侧边栏导航 ==========
    st.sidebar.header("导航菜单")
    app_mode = st.sidebar.radio(
        "请选择功能模块",
        ["🏠 数据看板", "🔗 技能图谱", "💬 智能问答"]
    )

    # ========== 数据加载增强版 ==========
    @st.cache_data
    def load_job_data():
        try:
            encodings = ['utf-8', 'gbk', 'gb18030']
            for enc in encodings:
                try:
                    df = pd.read_csv("招聘数据集(含技能列表）.csv", encoding=enc)
                    break
                except Exception as e:
                    print(f"尝试以{enc}编码读取文件时出错: {e}")
                    continue
            else:
                raise FileNotFoundError("无法解码文件或文件不存在")

            column_mapping = {
                'positionName': 'position',
                'workYear': 'experience',
                'education': 'education',
                'city': 'city',
                'salary': 'salary',
                'companyFullName': 'company'
            }
            df = df.rename(columns=column_mapping)

            required_columns = ['position', 'city', 'salary', 'experience', 'education', 'company', 'skill_list']
            missing_cols = [col for col in required_columns if col not in df.columns]
            if missing_cols:
                st.error(f"数据文件缺少必要列：{missing_cols}")
                st.stop()

            if df['skill_list'].isnull().all():
                st.error("技能字段全部为空，请检查数据集")
                st.stop()

            # 计算平均薪资
            def parse_salary(salary_str):
                if pd.isna(salary_str):
                    return None
                salary_str = str(salary_str).lower().replace('k', '').replace('w', '').replace('万', '')
                salary_parts = re.findall(r'\d+\.?\d*', salary_str)
                if not salary_parts:
                    return None
                if '-' in salary_str:
                    avg = (float(salary_parts[0]) + float(salary_parts[1])) / 2
                else:
                    avg = float(salary_parts[0])
                return avg

            df['avg_salary'] = df['salary'].apply(parse_salary)

            return df

        except Exception as e:
            st.error(f"数据加载失败：{str(e)}")
            st.stop()

    # ========== 页面路由 ==========
    try:
        data = load_job_data()

        if app_mode == "🏠 数据看板":
            render_data_analysis(data)

        elif app_mode == "🔗 技能图谱":
            render_skill_graph(data)

        elif app_mode == "💬 智能问答":
            render_ai_chat(data)

    except Exception as e:
        st.error(f"系统错误：{str(e)}")
        st.stop()

if __name__ == "__main__":
    main()